<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图-->
    <el-card class="box-card" style="width:100%">
      <!-- 添加按钮 -->
      <el-button type="primary" @click="addRole">添加角色</el-button>
      <!-- 角色列表区域 -->
      <el-table :data="rolesList" border stripe>
        <!-- 权限区域 -->
        <el-table-column type="expand">
          <!-- 展开行 -->
          <template slot-scope="scope">
            <el-row
              class="border_bottom"
              :class="index === 0 ? 'border_top':''"
              v-for="(item1,index) in scope.row.children"
              :key="item1.id"
            >
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag>{{ item1.authName }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级的权限 -->
              <el-col :span="19">
                <el-row v-for="item2 in item1.children" :key="item2.id">
                  <!-- 二级权限名称 -->
                  <el-col :span="8">
                    <el-tag type="success">{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级的权限 -->
                  <el-col :span="16">
                    <el-tag
                      @close="removeTag(scope.row,item3.id)"
                      closable
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="400px">
          <template slot-scope="scope">
            <!-- 编辑 -->
            <el-button type="primary" icon="el-icon-edit" size="mini">编辑</el-button>
            <!-- 删除 -->
            <el-button type="danger" icon="el-icon-delete" size="mini">删除</el-button>
            <!-- 分配角色 -->
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="setRole(scope.row)"
            >分配角色权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分配权限角色 -->
    <el-dialog title="分配角色权限" :visible.sync="setRightsdialogVisible" width="50%">
      <!-- 树形控件 -->
      <el-tree
        :data="rights"
        :props="defaultProps"
        show-checkbox
        default-expand-all
        :default-checked-keys="defaultKeys"
        node-key="id"
        @close="setRolerights"
        ref="tree"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightsdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setroleRighs">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 点击添加角色 -->
    <el-dialog title="添加角色" :visible.sync="addRoledialogVisible" width="50%">
      <el-form label-width="80px">
        <el-form-item label="角色名称">
          <el-input></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRoledialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoledialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      rolesList: [],
      setRightsdialogVisible: false,
      rights: [],
      defaultProps: {
        // 告诉组件内部我们要用children进行嵌套
        children: 'children',
        // 告诉组件内部显示哪个数据
        label: 'authName'
      },
      // 默认选中
      defaultKeys: [],
      rolesId: '',
      addRoledialogVisible: false
    }
  },

  created () {
    this.getRolesList()
  },

  methods: {
    // 获取数据列表
    async getRolesList () {
      const { data: res } = await this.$axios.get('/roles')
      // console.log(res)
      if (res.meta.status !== 200) { return this.$message.error('获取角色数据失败') }
      this.rolesList = res.data
      // console.log(this.rolesList)
    },
    // 删除权限操作
    removeTag (row, rightId) {
      // 提示弹出框
      this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          // 点击确定
          const { data: res } = await this.$axios.delete(
            `roles/${row.id}/rights/${rightId}`
          )
          console.log(res)
          if (res.meta.status !== 200) return this.$message.error('删除失败')
          row.children = res.data
          this.$message.success('删除成功')
        })
        .catch(() => {
          this.$message('取消删除')
        })
    },
    // 分配角色权限
    setRole (row) {
      this.setRightsdialogVisible = true
      // 调用递归函数
      this.getAllkeys(row)
      this.rolesId = row.id
      // 调用获取的数据
      this.getRightsList()
    },
    // 递归获取keys
    getAllkeys (row) {
      // console.log(row)
      if (!row.children) {
        return this.defaultKeys.push(row.id)
      }
      row.children.forEach((item) => {
        this.getAllkeys(item)
      })
    },
    // 关闭清空选项
    setRolerights () {
      this.defaultKeys = []
    },
    // 获取权限数据
    async getRightsList () {
      const { data: res } = await this.$axios.get('rights/tree')
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error('获取数据失败')
      this.rights = res.data
    },
    // 点击确定分配权限
    async setroleRighs () {
      // console.log(this.rolesId)
      const checkedKeys = this.$refs.tree.getCheckedKeys()
      const HalfCheckedKeys = this.$refs.tree.getHalfCheckedKeys()
      const allKeys = [...checkedKeys, ...HalfCheckedKeys]
      // console.log(allKeys)
      const { data: res } = await this.$axios.post(
        `roles/${this.rolesId}/rights`,
        {
          rids: allKeys.join(',')
        }
      )
      if (res.meta.status !== 200) return this.$message.error('更新失败')
      this.$message.success('更新成功')
      this.setRightsdialogVisible = false
      this.getRolesList()
    },
    // 点击添加角色
    addRole () {
      this.addRoledialogVisible = true
    }
  }
}
</script>

<style scoped lang='less'>
.el-tag {
  margin: 7px;
}
.el-row {
  display: flex;
  align-items: center;
}
.border_top {
  border-top: 1px solid #eee;
}
.border_bottom {
  border-bottom: 1px solid #eee;
}
</style>
